var list = new ArrayList();
var yyyy_MM_dd_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
var yyyyMMdd_PARSER = new SimpleDateFormat("yyyyMMdd");
var yyyy_MM_dd_HH_mm_ss_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
var yyyy_MM_FORMAT = new SimpleDateFormat("yyyy-MM");
var loginHtml = "";
var v6_ceb_java_funcs = {
    openHomePage : function(){
        //打开页面判断代理是否异常
        loginHtml = get("https://www.cebbank.com/per/prePerlogin.do?_locale=zh_CN");
        storeDataToFile(context, loginHtml, "login-01.html")
    },

    checkProxyAvailable: function(){
        logger.info("任务taskKey = {}, 进入到检查登录是否有代理IP异常方法", context.get(LUA_TASK_KEY));
        //判断是否代理异常的function
        var isCorrectFunc = function(loginHtml){
            var doc = Jsoup.parse(loginHtml);
            return (doc!=null && doc.select(".loginrtModule")!=null)
        }
        //获取异常信息的方法function
        var getErrorMsgFunc = function(loginHtml) {
            return "代理ip异常";
        }
        //返回信息
        return assertTrueOrThrowException(loginHtml, isCorrectFunc, getErrorMsgFunc)
    },
    checkTargetWebsiteAvailable: function(){
        return true;
    },
    checkControlAvailable:function(){
        //校验是否有控件异常
        logger.info("taskKey={},光大银行统一入口，开始校验是否有控件异常",context.get(LUA_TASK_KEY));
        var doc = Jsoup.parse(loginHtml);
        var controlType = doc.select("#powerpassForLogin") == null ? null:doc.select("#powerpassForLogin").attr("type");
        //用于获取控件检测结果的function
        var isCorrectFunc = function(controlType){
            if(controlType!=null && controlType.contains("application/npSecEditCtlAdv.CEB.x86")){
                //光大银行控件异常
                logger.info("taskKey={},光大银行控件升级或者控件不可用",context.get(LUA_TASK_KEY));
                return false;
            }else{
                return true;
            }
        }
        //用户获取控件检测错误信息的function
        var getErrorMsgFunc = function(controlType) {
            return "控件检测失败，控件未安装或者控件升级";
        }
        return assertTrueOrThrowException(controlType, isCorrectFunc, getErrorMsgFunc)
    },
    needRefreshHomePageOrNot : function() {
        return equals(context.get("currentErrorCode"), BALO_99602_40)
    },
    needResetEnvironment:function(){
        return true;
    },

    login:function(){
        //判断登录方式输入用户名和密码
        var loginTypeStatus = false;
        if (equals(LoginType.USERNAME.toString(),context.get(LUA_TASK_LOGIN_TYPE))) {
            var userName = getLoginParams(context)[0];
            set_input_text_by_id("skey", userName);
            loginTypeStatus = true;
        } else if (equals(LoginType.CARDNO.toString(),context.get(LUA_TASK_LOGIN_TYPE))) {
            var cardNO = getLoginParams(context)[0];
            set_input_text_by_id("skey", cardNO);
            loginTypeStatus = true;
        }else{
            logger.info("taskKey={},光大银行登录方式错误",context.get(LUA_TASK_KEY));
            throw new BankException(BankConstants.BALO_22102_10, "登录方式错误");
            loginTypeStatus = false;
        }
        //校验登录方式正确性
        var isLoginTypeCorrectFunc = function (loginTypeStatus) {
            return loginTypeStatus;
        }
        //获取登录方式错误信息
        var getLoginTypeErrorMsg = function(loginTypeStatus){
            return "用户名密码校验未通过"
        }
        assertTrueOrThrowException(loginTypeStatus, isLoginTypeCorrectFunc, getLoginTypeErrorMsg);

        //输入密码点击确定按钮
        var passWord = context.get(LUA_TASK_TOKEN);
        show();//打开窗口休眠两秒，输入密码
        Thread.sleep(2000);
        //输入密码
        var a = luaFuncs.input_password_gd(passWord);
        hide();
        if (a.equals("no")) {
            show();
            var path = luaFuncs.store_Img_gd();
            hide();
            logger.info("任务" + context.get(LUA_TASK_KEY) + "首页信息：超时信息-路径" + path);
        } else if (a.contains("return is null") || a.length() != passWord.length()) {
            show();
            var path = luaFuncs.store_Img_gd();
            logger.error("密码输入异常，输入的长度 {} 不等于真正的长度 {}，返回结果={},截图存储路径={}", a.length(),passWord.length(),a,path);
            hide();
        }

        //获取密码输入流程正确性
        var isInputPwdCorrectFunc = function (a) {
            if(a.contains("return is null") || a.length() != passWord.length() || a.equals("no")){
                return false;
            }else{
                return true;
            }
        }
        //获取密码输入的错误信息
        var getInputPwdErrMsg = function (a) {
            return "密码因控件输入错误";
        }
        assertTrueOrThrowException(a, isInputPwdCorrectFunc, getInputPwdErrMsg);

        //点击登录按钮获取登录结果
        Thread.sleep(1000);
        //登录
        var html = luaFuncs.do_login_buttn();
        storeDataToFile(context, html, "login-02.html")
        logger.info("任务" + context.get(LUA_TASK_KEY) + "登录信息：节点信息-" + html);
        //返回错误信息，如果等于yes 判断是否登录成功，否则都是登录失败，处理掉按标签的内容
        //获取登录流程正确性
        var isLoginStepOnePwdCorrectFunc = function (html) {
            var theIndexHtml = get_html();
            storeDataToFile(context, theIndexHtml, "theIndexHtml.html")
            return html.equals("yes");
        }
        //获取登录第一步的异常信息
        var getLoginStepOneErrMsg=function (html) {
            return html.replace(/\，有问题请点击\<A[\s\S]*\/A\>/g,"");
        }
        assertTrueOrThrowException(html, isLoginStepOnePwdCorrectFunc, getLoginStepOneErrMsg);

        //获取登录后页面，看是否存在其他问题 您的网银登录密码已超过6个月，为了您的账户安全，请及时更换网银登录密码！
        var html2 = luaFuncs.get_html_gd();
        storeDataToFile(context, html2, "errorHtml.html")
        //获取登录流程正确性
        var isLoginStepTwoPwdCorrectFunc = function (html2) {
            if(!(html2.contains("登录密码过期提示") || html2.contains("为了更安全的使用我行网上银行，请您设置登录密码和防伪信息"))){
                return true;
            }
            return false;
        }
        //获取登录第一步的异常信息
        var getLoginStepTwoErrMsg=function (html2) {
            //判断是否包含登录密码过期的提示
            if(html2.contains("登录密码过期提示")){
                return "您登录密码已超过六个月未修改，为了您网银的安全使用，请修改登录密码";
            }else if(html2.contains("为了更安全的使用我行网上银行，请您设置登录密码和防伪信息")){
                return "您的密码过于简单，请登录官网重置";
            }else{
                return "新出现的错误信息";
            }
        }
        assertTrueOrThrowException(html2, isLoginStepTwoPwdCorrectFunc, getLoginStepTwoErrMsg);

        //判断是否需要短信验证码
        logger.info("taskkey={},光大银行开始校验是否需要短信验证码",context.get(LUA_TASK_KEY));
        var flag = luaFuncs.check_sms_input();
        var smsCheckMsg = "";
        //需要短信验证码
        if (flag.equals("true")) {
            logger.info(context.get(LUA_TASK_KEY) + "请输入短信验证码：" );
            // 获取短信验证码
            var verifyMessage = waitSmsCodeBySeconds(context,120);
            Thread.sleep(1000);
            logger.info(context.get(LUA_TASK_KEY) + "短信验证码为：{}", verifyMessage);
            //输入短信验证码
            luaFuncs.input_sms_code(verifyMessage);
            //输入完短信验证码后再次判断是否需要短信验证码
            var check = luaFuncs.check_sms_input();
            //不需要短信，说明短信验证码输入正确，否则说明短信验证码错误
            if (check.equals("false")) {
                smsCheckMsg = "true";
            } else {
                show();
                //保存页面的路径
                var path = luaFuncs.store_Img_gd();
                hide();
                logger.info("任务" + context.get(LUA_TASK_KEY) + "登录信息：-路径:"+path);
                smsCheckMsg = "验证码错误或已超时";
            }
        } else {
            //首页信息
            var html = luaFuncs.get_first_html();
            storeDataToFile(context, html, "firstHtml.html")
            var doc = Jsoup.parse(html);
            //获取页面上的某元素信息
            var mainRight = doc.getElementById("mainRight");
            //判断某元素是否为空，来判断是否
            if(mainRight != null){
                smsCheckMsg = "true";
            }else{
                show();
                var path = luaFuncs.store_Img_gd();
                hide();
                logger.info("任务" + context.get(LUA_TASK_KEY) + "登录信息：-路径:"+path);
                smsCheckMsg = "登录成功后页面跳转超时"
            }
        }
        //校验验证码输入流程的正确性
        var isInputSmsCorrectFunc = function (smsCheckMsg) {
            if(smsCheckMsg.equals("true")){
                return true;
            }else{
                return false;
            }
        }
        //获取验证码输入的错误信息
        var getInputSmsErrMsg = function (smsCheckMsg) {
            return smsCheckMsg;
        }
        assertTrueOrThrowException(smsCheckMsg, isInputSmsCorrectFunc, getInputSmsErrMsg);
    },
    crawl:function () {
        //获取首页信息
        commFuns.get_index_html();
        //解析首页信息，获取用户名
        commFuns.parse_index_html();
        //获取借记卡账户管理页面
        debit_commFuns.get_debit_card_base_info();
        //获取信用卡账户管理页面
        credit_commFuns.get_credit_card_base_info();
        //解析信用卡页面，借记卡页面，获取基本的卡数量和基本信息
        commFuns.parse_card_size();
        //输入卡数量，构建表头
        commFuns.create_credit_card_all_data_list();
        //获取构建好的表头信息
        var data_list = context.get(ALL_DATA);
        var credit_base_info_list = context.get("credit_base_info_list");
        //首先解析信用卡信息
        for (var i = 0;i < data_list.size();i++){
            var creditCardAllData = data_list.get(i);
            if (creditCardAllData.getCardType().equals("信用卡")) {
                //开始注入基本信息
                var index = 0;
                credit_commFuns.init_credit_card_all_data(creditCardAllData,index);

                index++;
            }
        }

        var debit_base_info_list = context.get("debit_base_info_list");









        //解析信用卡信息
        var creditHtml = ajax_get("https://www.cebbank.com/per/FP060101.do?enterPath=1");
        storeDataToFile(context, creditHtml, "creditHtml.html")
        if(!creditHtml.contains("您尚未配置信用卡信息")){
            logger.info("任务【{}】，发现有信用卡信息，进行抓取",context.get(LUA_TASK_KEY));
            creditCrawl(firstMap,creditHtml);
        }
        //解析借记卡信息
        debitCrawl(firstMap);
        context.put("debit_data", list);

    },
    exitLogin: function () {

    }
}




/**
 * 抓取借记卡信息
 * @param firstMap
 */
function debitCrawl(firstMap) {
    var EZ_NAME = firstMap.get("EZ_NAME");
    logger.info("任务：{}，开始进行借记卡信息抓取",context.get(LUA_TASK_KEY));
    //获取储蓄卡列表
    var debitHtml = ajax_get("https://www.cebbank.com/per/FP020201.do?enterPath=1");
    var debitDoc = Jsoup.parse(debitHtml);
    //保存页面
    storeDataToFile(context, debitHtml, "debitHtml.html");
    //通过id获取
    var bh = debitDoc.getElementById("bh");
    if(bh == null){
        logger.info("任务：{}，借记卡列表获取失败，借记卡抓取结束",context.get(LUA_TASK_KEY));
        return;
    }
    //var tables = bh.getElementsByTag("table");
    //if(tables !=null && (tables.size() == 14 ||tables.size()==8)){
        var parentTables = debitDoc.select("#bh > table:nth-child(3)")
        if(parentTables!=null){
            var cardTables = parentTables.select(".txt02.table1.mar01");
            for(var s=0;s<cardTables.size();s++){
                var cardInput = cardTables.get(s).select("[class='td2']").get(0);
                var inputs = cardInput.select("td");
                //获取卡片类型
                var type = inputs.get(3).text();
                logger.info("任务：{}，获取到卡类型："+type,context.get(LUA_TASK_KEY));
                //卡片是信用卡,循环遍历信用卡结果集将基本信息放入对应的信用卡信息
                if(type.contains("信用卡")){
                    for each(var creditCardAllData in list){
                        var full_card_name = creditCardAllData.getFullCardNum();
                        var full_card = inputs.get(2).text().replaceAll(" ", "");
                        if(full_card.equals(full_card_name)){
                            //开卡银行
                            var open_bank = inputs.get(4).text();
                            //持卡人姓名
                            var name_on_card = inputs.get(1).text();
                            creditCardAllData.setOpenBank(open_bank);
                            creditCardAllData.setNameOnCard(name_on_card);
                        }
                    }
                    continue;
                }else{
                    // 声明存储对象
                    var creditCardAllData = new CreditCardAllData();
                    // 声明存储金额列表
                    var deposits = new ArrayList();
                    // 声明账单列表
                    var bills = new ArrayList();
                    creditCardAllData.setBills(bills);
                    creditCardAllData.setDeposits(deposits);
                    //卡类型
                    creditCardAllData.setCardType("借记卡");
                    //持卡人姓名
                    var name_on_card = inputs.get(1).text();
                    //卡号
                    var full_card_num = inputs.get(2).text();
                    full_card_num = full_card_num.replaceAll(" ", "");
                    //开户银行
                    var open_bank = inputs.get(4).text();
                    //持卡人姓名
                    creditCardAllData.setNameOnCard(name_on_card);
                    //完整卡号
                    creditCardAllData.setFullCardNum(full_card_num);
                    //开户银行
                    creditCardAllData.setOpenBank(open_bank);
                    //卡号后四位
                    creditCardAllData.setCardNum(full_card_num.substring(full_card_num.length()-4,full_card_num.length()));
                    //现金额度
                    creditCardAllData.setCashLimit(null);
                    //信用额度
                    creditCardAllData.setCreditLimit(null);
                    //可用取现额度
                    creditCardAllData.setCashBalance(null);
                    //查询储蓄
                    var cardTable = cardTables.get(s);
                    var paramsStr = cardTable.select("a").get(0).attr("onclick")
                    paramsStr = getGroupByIndex("showHidden\\((.*)\\);", paramsStr, 1).replace(/\'/g,"");
                    var paramsArr = paramsStr.split(",")
                    if(paramsArr.length<=0){
                        return;
                    }
                    var postdata = new HashMap();
                    postdata.put("_viewReferer", "query/queryAsyError");
                    postdata.put("kind", "br");
                    postdata.put("AcNo", paramsArr[5]);
                    postdata.put("AcType", paramsArr[6]);
                    postdata.put("AcOrganId", paramsArr[7]);
                    //将上一步获取的url拼接
                    var depositUrl = "https://www.cebbank.com/per/FP020207.do";
                    //get请求获取借记卡信息
                    var debitDepositHtml = ajax_post(depositUrl,postdata);
                    //保存页面
                    storeDataToFile(context, debitDepositHtml, s+"_debitDepositHtml.html")
                    try{
                        //保存卡信息
                        paraseDepositHtml(debitDepositHtml,creditCardAllData,deposits);
                        logger.info("任务：{}，卡信息解析完成",context.get(LUA_TASK_KEY));
                    }catch ( e) {
                        logger.error("任务：{}，借记卡储蓄信息：解析失败,error:{}",context.get(LUA_TASK_KEY),e);
                    }
                    //查询明细
                    var debitDtailDoc = Jsoup.parse(debitDepositHtml);
                    var table1s = debitDtailDoc.select("[class='txt02 txt_zt table1']");
                    var table1 = table1s.get(0);
                    //每张借记卡 只查询正常人民币和美元账户的收支明细
                    var shouzhis = table1.select("[class='txt03 txt_line shouzhi']");
                    var expList = new ArrayList();
                    var tempCard = "";

                    for(var j = 0 ; j < shouzhis.size()-1 ; j++){
                        //获取某元素的onclick属性
                        var onclicks = shouzhis.get(j).attr("onclick");
                        //按'将获取到的url进行分割
                        var clickParams = onclicks.split("'");
                        //拼接获取到的url
                        var detailUrl = "https://www.cebbank.com/per/"+clickParams[1];
                        //发送请求获取账单信息
                        var detailShortHtml = ajax_get(detailUrl);
                        //保存信息
                        storeDataToFile(context, detailShortHtml, s+"_debitDtailList_"+j+".txt");
                        //获取不到卡号信息，直接跳出

                        if(!(detailShortHtml.contains("_tokenName") && detailShortHtml.contains("_viewReferer") && detailShortHtml.contains("AcNo")
                            && detailShortHtml.contains("AcType") && detailShortHtml.contains("AcCur") && detailShortHtml.contains("AcSeqNo") &&
                            detailShortHtml.contains("CHFlag") && detailShortHtml.contains("CifName") && detailShortHtml.contains("QISHBS3") &&
                            detailShortHtml.contains("TranId") && detailShortHtml.contains("OldBeginDate") && detailShortHtml.contains("OldEndDate") && detailShortHtml.contains("flag")
                            && detailShortHtml.contains("isCXflag") && detailShortHtml.contains("helpID") && detailShortHtml.contains("yanID") && detailShortHtml.contains("counter1")
                            && detailShortHtml.contains("counter2") && detailShortHtml.contains("counter3") && detailShortHtml.contains("isSearch")
                            && detailShortHtml.contains("BeginDatehidden") && detailShortHtml.contains("EndDatehidden") && detailShortHtml.contains("gjsearch") && detailShortHtml.contains("SSCFlag"))){
                            logger.info("未获取到卡号信息，跳出")
                            continue;
                        }
                        //可以抓取13个月的账单，最长跨度六个月，分三次进行
                        for(var x = 1; x < 4 ; x++){
                            var dateMap = getBeginAndEndDate();
                            var beginDate = dateMap.get("beginDate"+x);
                            var endDate = dateMap.get("endDate"+x);
                            var map = new HashMap();
                            //获取请求参数
                            paraseDetailParams(detailShortHtml,map,beginDate,endDate);
                            //发请求获取账单信息
                            var detailTxt = ajax_post("https://www.cebbank.com/per/FP020205.do", map);
                            //保存数据
                            storeDataToFile(context, detailTxt, s+"_detailTxt_"+j+beginDate+".txt")
                            try{
                                //获取消费记录
                                paraseDetailTxt(detailTxt,expList,j,creditCardAllData);
                            }catch ( e) {
                                logger.error("任务:{},借记卡账单信息：解析失败,error:{}",context.get(LUA_TASK_KEY),e + e.lineNumber);
                            }
                        }
                    }

                    // 获取账单列表
                    var calendar = Calendar.getInstance();
                    for (var i = 0; i < 13; i++) {
                        var year = calendar.get(Calendar.YEAR);
                        var month = calendar.get(Calendar.MONTH) + 1; // calendar.get(Calendar.MONTH)返回值得第一个月为0，所以+1。
                        var yearMoth = year + "-" + getYearOrDayString(month);
                        logger.info("任务:{},账单信息：账单月份:{}",context.get(LUA_TASK_KEY),yearMoth);
                        try {
                            getDetailBillByDateNew(expList, bills,yearMoth);
                        } catch ( e) {
                            logger.error("任务:{},账单信息，账单月份：{}：解析异常:{}",context.get(LUA_TASK_KEY),yearMoth,e);
                        }
                        calendar.add(Calendar.MONTH, -1);
                    }
                    list.add(creditCardAllData);
                }
            }
        }
   // }
}

/**
 * 解析信用卡信息
 * @param creditCardAllData
 * @param debitDepositHtml
 */
function paraseCreditHtml(creditCardAllData, debitDepositHtml) {
    var doc = Jsoup.parse(debitDepositHtml);
    var tables = doc.select("[class='txt02 txt_zt table1']");
    var table = tables.get(0);
    var trs = table.select("[class='td2']");
    for(var i = 0;i <= 0;i++){
        var tr = trs.get(i);
        var tds = tr.select("td");
        var balance = tds.get(6).text();
        var transCurrency = tds.get(1).text();
        var deposit_date = tds.get(4).text();
        var deposit_type = tds.get(0).text();
        var buffer = new StringBuffer(deposit_date);
        buffer.insert(4, "-");
        buffer.insert(7, "-");
        //开卡时间
        creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(buffer.toString()));
    }
}

/**
 * 抓取信用卡信息
 * @param firstMap
 */
function creditCrawl( firstMap,creditHtml) {
    var EZ_NAME = firstMap.get("EZ_NAME");
    logger.info("任务；{}，信用卡开始抓取",context.get(LUA_TASK_KEY));
    //获取信用卡卡列表

    //解析页面
    var doc = Jsoup.parse(creditHtml);
    //获取账单信息
    var cardIds = doc.select("[name='CardId']").get(0);
    var options = cardIds.getElementsByTag("option");
    for(var i=0;i<options.size();i++){
        var cardText = options.get(i).text();
        //判断是否为附属卡 -- 附属卡不做抓取
        if(cardText.contains("附属卡")){
            logger.info("任务：{}，判断为附属卡，跳出当前卡循环",context.get(LUA_TASK_KEY));
            continue;
        }
        // 声明存储对象
        var creditCardAllData = new CreditCardAllData();
        // 声明存储金额列表
        var deposits = new ArrayList();
        // 声明账单列表
        var bills = new ArrayList();
        creditCardAllData.setBills(bills);
        creditCardAllData.setDeposits(deposits);
        //	creditCardAllData.setNameOnCard(EZ_NAME);
        var cards = cardText.split("/");
        //获取卡号
        var full_card_num = cards[0];
        //卡号后四位
        var card_num = full_card_num.substring(full_card_num.length()-4,full_card_num.length());
        //完整卡号
        creditCardAllData.setFullCardNum(full_card_num);
        //卡号后四位
        creditCardAllData.setCardNum(card_num);
        //卡类型
        creditCardAllData.setCardType("信用卡");
        //银行
        creditCardAllData.setBankName("光大银行");
        //卡的编号
        creditCardAllData.setCardId(UUID.randomUUID().toString());
        //现金额度
        creditCardAllData.setCashBalance(null);
        //获取请求参数
        var CardId = options.get(i).attr("value");
        //解析页面获取请求参数
        var delcounter = doc.select("[name='delcounter']").get(0).attr("value");
        var _tokenName = doc.select("input[name='_tokenName']").get(0).attr("value")
        var helpID = doc.select("input[name='helpID']").get(0).attr("value");
        var yanID = doc.select("input[name='yanID']").get(0).attr("value");
        var _viewReferer = doc.select("input[name='_viewReferer']").get(0).attr("value");
        var postdata = new HashMap();
        postdata.put("delcounter", delcounter);
        postdata.put("CardId", CardId);
        postdata.put("_tokenName", _tokenName);
        postdata.put("helpID", helpID);
        postdata.put("yanID", yanID);
        postdata.put("_viewReferer", _viewReferer);
        //发请求获取信用卡基本信息
        var baseInfoHtml = ajax_post("https://www.cebbank.com/per/FP060102.do", postdata);
        //保存页面信息
        storeDataToFile(context, baseInfoHtml, i+"_baseInfoHtml.html")
        var unMap = new HashMap();
        try{
            //解析信用卡基本信息
            paraseBaseInfoHtml(baseInfoHtml,creditCardAllData,unMap);
        }catch ( e) {
            logger.error("任务：{}，信用卡基本信息：解析失败，card_no:{},error：{}",context.get(LUA_TASK_KEY),full_card_num,e);
        }
        logger.info("任务：{}，开始解析信用卡已出账单,card_no:{}",context.get(LUA_TASK_KEY),full_card_num);
        //已出账单查询
        var billListHtml = ajax_get("https://www.cebbank.com/per/FP060201.do?enterPath=1");
        storeDataToFile(context, billListHtml, i+"_billListHtml.html")
        var billDoc = Jsoup.parse(billListHtml);
        var billIds = billDoc.select("[name='CardId']").get(0);
        var billoptions = billIds.getElementsByTag("option");
        for(var j=0;j<billoptions.size();j++){
            var billText = billoptions.get(j).text();
            //如果billText包含卡号后四位
            if(billText.contains(full_card_num)){
                //获取其value值，获取请求参数
                var billId = billoptions.get(j).attr("value");
                var billdelcounter = billDoc.select("[name='delcounter']").get(0).attr("value");
                var postbill = new HashMap();
                postbill.put("delcounter", billdelcounter);
                postbill.put("CardId", billId);
                postbill.put("Org", "102");
                parseParams(billDoc,postbill,"form1");
                //请求获取账单信息
                var billInfoHtml = ajax_post("https://www.cebbank.com/per/FP060202.do", postbill);
                storeDataToFile(context, billInfoHtml, i+"_billInfoHtml.html")
                //判断是否有账户信息
                if(billInfoHtml.contains("文件上未发现帐户")){
                    continue;
                }
                //解析账单信息--进行36个月的循环，遇到账单周期小于开卡日期以及超过账单周期的跳出循环
                for(var n = 0 ; n < 36 ; n++){
                    var calendarCredit = Calendar.getInstance();
                    if(n >= 1){
                        calendarCredit.add(Calendar.MONTH, n * -1);
                    }
                    var bill_moth = yyyy_MM_FORMAT.format(calendarCredit.getTime());
                    var bill_day = bill_moth + "-01";
                    var num = 1;
                    var billAllData = new BillAllData();
                    billAllData.setBankName("光大银行");
                    logger.info("任务：{}，信用卡已出账单抓取，当前月份：{},card_no:{}",context.get(LUA_TASK_KEY),bill_moth,full_card_num);
                    //账单日
                    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(bill_day));
                    //账单编号
                    billAllData.setBillId(UUID.randomUUID().toString());
                    //账单月份
                    billAllData.setBillMonth(bill_moth);
                    //账单类型
                    billAllData.setBillType("DONE");
                    //预借现金额度
                    billAllData.setCashLimit(null);
                    //信用卡额度
                    billAllData.setCreditLimit(null);
                    //上期账单金额
                    billAllData.setLastBalance(null);
                    //上期还款金额
                    billAllData.setLastPayment(null);
                    //利息
                    billAllData.setInterest(null);
                    //预借现金额度美元
                    billAllData.setUsdCashLimit(null);
                    //信用卡额度美元
                    billAllData.setUsdCreditLimit(null);
                    //利息美元
                    billAllData.setUsdInterest(null);
                    //上期账单金额美元
                    billAllData.setUsdLastBalance(null);
                    //上期还款金额美元
                    billAllData.setUsdLastPayment(null);
                    //最低还款金额美元
                    billAllData.setUsdMinPayment(null);
                    //本期账单金额美元
                    billAllData.setUsdNewBalance(null);
                    //本期新增款额美元
                    billAllData.setUsdNewCharges(null);
                    if(n + 1 < 36){
                        //获取前一个月的月份信息
                        var lastMonthCalender = Calendar.getInstance();
                        lastMonthCalender.set(bill_day.substring(0,4),bill_day.substring(5,7),bill_day.substring(8,10))
                        lastMonthCalender.add(Calendar.MONTH, -1);
                        var lastMonth = yyyy_MM_FORMAT.format(lastMonthCalender.getTime());
                        print(lastMonth)
                        for each(var billAllData2 in bills){
                            var newmonth = billAllData2.getBillMonth();
                            if(lastMonth.equals(newmonth)){
                                billAllData.setLastBalance(billAllData2.getNewBalance());
                            }else{
                                billAllData.setLastBalance(null);
                            }
                        }
                    }else{
                        billAllData.setLastBalance(null);
                    }
                    var billDetailMap = new HashMap();
                    billDetailMap.put("StartNo", "");
                    //获取请求参数
                    parseDetailParams(billInfoHtml,billDetailMap,"form1",num);
                    billDetailMap.put("BillCycle", bill_day);
                    billInfoHtml = ajax_post("https://www.cebbank.com/per/FP060202.do", billDetailMap);
                    var detailDoc = Jsoup.parse(billInfoHtml)
                    if(billInfoHtml.contains("账单周期小于开卡日期") || (detailDoc.select(".table1.txt_hui.mar01") == null ? 0 : detailDoc.select(".table1.txt_hui.mar01").select("tr").size()) <=1){
                        logger.info("任务：{}，信用卡抓取账单，周期小于开卡日期或者超出最大周期,结束循环,card_no:{}",context.get(LUA_TASK_KEY),full_card_num)
                        break;
                    }
                    //保存页面
                    storeDataToFile(context, billInfoHtml, i+"_billDetailHtml_"+n+"_1.html")
                    var shopping_sheets = new ArrayList();
                    try{
                        var flag = true;
                        var pageFlag = true;
                        var t = 1;
                        //获取消费记录
                        pageFlag = parseDetailHtml(billAllData,billInfoHtml,bill_day,flag,shopping_sheets,t);
                        flag = false;
                        num = num + 1;
                        while(pageFlag){
                            //获取请求参数
                            parseDetailParams(billInfoHtml,billDetailMap,"form1",num);
                            billDetailMap.put("BillCycle", bill_day);
                            billInfoHtml = ajax_post("https://www.cebbank.com/per/FP060202.do", billDetailMap);
                            storeDataToFile(context, billInfoHtml, i+"_billDetailHtml_"+n+"_"+num+".html")
                            //获取消费记录
                            pageFlag = parseDetailHtml(billAllData,billInfoHtml,bill_day,flag,shopping_sheets,t);
                            num = num + 1;
                        }
                    }catch ( e) {
                        logger.error("任务:{},card_no:{},信用卡已出账单：解析失败,error:{}",context.get(LUA_TASK_KEY),full_card_num,e);
                    }
                    var money = new BigDecimal("0.0");
                    for each (var exp in shopping_sheets){
                        //获取交易金额
                        var amount = exp.getAmountMoney();
                        //如果交易金额为正，将金额相加
                        if(amount.signum() == 1){
                            money = money.add(amount);
                        }
                    }
                    //本期新增款额
                    billAllData.setNewCharges(money);
                    var payment_money = new BigDecimal("0.0");
                    for each (var exp in shopping_sheets){
                        var payment_amount = exp.getAmountMoney();
                        //如果交易金额为负，将金额想减
                        if(payment_amount.signum() == -1){
                            payment_money = money.add(payment_amount);
                        }
                    }
                    //上期还款金额
                    billAllData.setLastPayment(payment_money);
                    billAllData.setShoppingSheets(shopping_sheets);
                    bills.add(billAllData);
                }
            }
        }
        //未出账单查询
        logger.info("任务：{}，开始解析信用卡未出账单,card_no:{}",context.get(LUA_TASK_KEY),full_card_num);
        var unbillListHtml = ajax_get("https://www.cebbank.com/per/FP060301.do?enterPath=1");
        storeDataToFile(context, unbillListHtml, i+"_unbillListHtml.html")
        //解析未出账单信息
        var unbillDoc = Jsoup.parse(unbillListHtml);
        var unbillIds = unbillDoc.select("[name='CardId']").get(0);
        var unbilloptions = unbillIds.getElementsByTag("option");
        for(var j=0;j<unbilloptions.size();j++){
            var billText = unbilloptions.get(j).text();
            //如果billText和卡号一样
            if(billText.contains(full_card_num)){
                var billAllData = new BillAllData();
                var num = 1;
                //银行
                billAllData.setBankName("光大银行");
                var cal = Calendar.getInstance();
                //月份加一
                cal.add(Calendar.MONTH, 1);
                var moth = yyyy_MM_dd_FORMAT.format(cal.getTime());
                //账单日
                billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(moth.substring(0,7)+"-01"));
                //账单编号
                billAllData.setBillId(UUID.randomUUID().toString());
                //账单月份
                billAllData.setBillMonth(moth.substring(0,7));
                //未出账单
                billAllData.setBillType("UNDONE");
                //现金额度
                billAllData.setCashLimit(null);
                //上期账单金额
                billAllData.setLastBalance(null);
                //上期还款金额
                billAllData.setLastPayment(null);
                //循环利息
                billAllData.setInterest(null);
                //现金额度美元
                billAllData.setUsdCashLimit(null);
                //信用卡额度美元
                billAllData.setUsdCreditLimit(null);
                //循环利息美元
                billAllData.setUsdInterest(null);
                //上期账单金额美元
                billAllData.setUsdLastBalance(null);
                //上期还款金额美元
                billAllData.setUsdLastPayment(null);
                //最低还款金额美元
                billAllData.setUsdMinPayment(null);
                //本期账单金额美元
                billAllData.setUsdNewBalance(null);
                //本期新增款额美元
                billAllData.setUsdNewCharges(null);
                var billId = unbilloptions.get(j).attr("value");
                var billdelcounter = unbillDoc.select("[name='delcounter']").get(0).attr("value");
                var postbill = new HashMap();
                postbill.put("delcounter", billdelcounter);
                postbill.put("CardId", billId);
                postbill.put("Org", "102");
                //获取请求参数
                parseParams(billDoc,postbill,"form1");
                //发送post请求获取未出账单信息
                var unbillInfoHtml = ajax_post("https://www.cebbank.com/per/FP060302.do", postbill);
                //保存页面
                storeDataToFile(context, unbillInfoHtml, i+"_unbillInfoHtml_0.html")
                var shopping_sheets = new ArrayList();
                try{
                    var flag = true;
                    var pageFlag = true;
                    var t = 1;
                    //解析未出账单信息
                    pageFlag = parseUnbillHtml(unbillInfoHtml,billAllData,t,flag,creditCardAllData,unMap,shopping_sheets);
                    flag = false;
                    num = num + 1;
                    while(pageFlag){
                        var unbillMap = new HashMap();
                        //获取未出账单参数
                        parseUnbillParams(unbillInfoHtml,unbillMap);
                        //通过发送post请求获取未出账单页面
                        unbillInfoHtml = ajax_post("https://www.cebbank.com/per/FP060302.do", unbillMap);
                        //保存页面
                        storeDataToFile(context, unbillInfoHtml, i+"_unbillInfoHtml_"+num+".html")
                        //解析未出账单信息
                        pageFlag = parseUnbillHtml(unbillInfoHtml,billAllData,t,flag,creditCardAllData,unMap,shopping_sheets);
                        num = num + 1;
                    }
                }catch ( e) {
                    logger.error("任务:{},card_no:{},信用卡未出账单,解析失败-{}",context.get(LUA_TASK_KEY),full_card_num,e);
                }
                var money = new BigDecimal("0.0");
                //循环消费记录
                for each (var exp in shopping_sheets){
                    //获取消费金额
                    var amount = exp.getAmountMoney();
                    //如果金额为正
                    if(amount.signum() == 1){
                        money = money.add(amount);
                    }
                }
                //本期账单金额
                billAllData.setNewBalance(money);
                cal.setTime(cal.getTime());
                //月份减一
                cal.add(Calendar.MONTH, -1);
                var currdate = cal.getTime();
                var currmoth = yyyy_MM_dd_FORMAT.format(currdate);
                currmoth = currmoth.substring(0, 7);
                for each (var billData in bills){
                    if(currmoth.equals(billData.getBillMonth())){
                        var currBalance = money.add(billData.getNewBalance());
                        //本期账单金额
                        billAllData.setNewBalance(currBalance);
                        //上期账单金额
                        billAllData.setLastBalance(billData.getNewBalance());
                    }
                }
                //计算上期还款金额
                var payment_money = new BigDecimal("0.0");
                for each (var exp in shopping_sheets){
                    var payment_amount = exp.getAmountMoney();
                    if(payment_amount.signum() == -1){
                        payment_money = money.add(payment_amount);
                    }
                }
                //上期还款金额
                billAllData.setLastPayment(payment_money);
                //本期新增款额
                billAllData.setNewCharges(money);
                billAllData.setShoppingSheets(shopping_sheets);
                bills.add(billAllData);
            }
        }
        list.add(creditCardAllData);
        logger.info("任务：{}，信用卡账单已经解析完成,card_no:{}",context.get(LUA_TASK_KEY),full_card_num);
    }
}

/**
 * 根据日期获取账单信息
 * @param expList
 * @param bills
 * @param yearMoth
 */
function getDetailBillByDateNew(expList, bills,  yearMoth) {
    var billAllData = new BillAllData();
    var shopping_sheets = new ArrayList();// 消费记录
    //银行
    billAllData.setBankName("光大银行");
    //账单编号
    billAllData.setBillId(UUID.randomUUID().toString());
    //分期
    billAllData.setInstallments(new ArrayList());
    //账单月份
    billAllData.setBillMonth(yearMoth);
    //账单日
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(yearMoth + "-" + "01"));
    //设置billtype
    billAllData.setBillType("");
    // 设置该类型为0
    var bigDecimal = null;
    // 以下数据页面无
    //最低还款额度
    billAllData.setMinPayment(bigDecimal);
    //利息
    billAllData.setInterest(bigDecimal);
    //上期账单金额
    billAllData.setLastBalance(bigDecimal);
    //上期还款金额
    billAllData.setLastPayment(bigDecimal);
    //本期新增款额
    billAllData.setNewCharges(bigDecimal);
    //本期账单金额
    billAllData.setNewBalance(bigDecimal);
    // 信用额度相关
    billAllData.setCreditLimit(bigDecimal);
    //预借现金额度
    billAllData.setCashLimit(bigDecimal);
    // 美元相关---------先暂且设置为0
    //预借现金额度
    billAllData.setUsdCashLimit(bigDecimal);
    //信用卡额度
    billAllData.setUsdCreditLimit(bigDecimal);
    //利息美元
    billAllData.setUsdInterest(bigDecimal);
    //上期账单金额美元
    billAllData.setUsdLastBalance(bigDecimal);
    //上期还款金额美元
    billAllData.setUsdLastPayment(bigDecimal);
    //最低还款金额美元
    billAllData.setUsdMinPayment(bigDecimal);
    //本期账单金额美元
    billAllData.setUsdNewBalance(bigDecimal);
    //本期新增款额美元
    billAllData.setUsdNewCharges(bigDecimal);
    var i = 1;
    for each (var exp in expList){
        //获取交易时间
        var trans_date = exp.getTransDate();
        if(DateFormatUtils.format(trans_date, "yyyy-MM-dd").contains(yearMoth)){
            //排序
            exp.setOrderIndex(i);
            shopping_sheets.add(exp);
            i=i+1;
        }
    }
    //本期账单金额
    billAllData.setNewBalance(bigDecimal);
    billAllData.setShoppingSheets(shopping_sheets);
    if(shopping_sheets.size() != 0){
        bills.add(billAllData);
    }
}

/**
 * 计算月份
 * @param num
 * @returns {string}
 */
function getYearOrDayString(num) {
    var mon = "";
    //如果传入的月份的长度为1，例如传入的月份是3
    if ((num + "").length == 1) {
        //符合条件，给传入的月份拼接0，此时月份为03
        mon = "0" + num + "";
    } else {
        //不符合条件，传入的月份是多少就给月份赋值为多少
        mon = num + "";
    }
    return mon;
}


/**
 * 获取消费记录
 * @param detailTxt
 * @param expList
 * @param j
 * @param creditCardAllData
 */
function paraseDetailTxt( detailTxt, expList,  j,  creditCardAllData) {
    logger.info("taskKey={},开始获解析最近六个月的消费记录",context.get(LUA_TASK_KEY))
    //判断是否查询到相应的消费记录
    if(detailTxt.contains("没有查询到相应记录")){
        return;
    }
    //将获取到的文本按换行进行分割
    var txt = detailTxt.split("\r\n");
    for(var i=18;i<txt.length;i++){
        if(txt[i].equals("") || txt[i].contains("此清单仅供参考")){
            return;
        }
        var contents = txt[i].split("\|");
        if(contents.length == 7){
            var exp = new Expense();
            var trans_date = (contents[0]==null || contents[0]==undefined) ? null : contents[0].trim();
            var amount_money1 = (contents[1]==null || contents[1]==undefined) ? null : contents[1].trim();
            var amount_money2 = (contents[2]==null || contents[2]==undefined) ? null : contents[2].trim();
            var balance = (contents[3]==null || contents[3]==undefined) ? null:contents[3].trim();
            var opposite_card_no = (contents[4]==null || contents[4]==undefined) ? null:contents[4].trim();
            var name_on_opposite_card = (contents[5]==null || contents[5]==undefined) ? null:contents[5].trim();
            var description = (contents[6]==null || contents[6]==undefined) ? null:contents[6].trim();
            //交易时间
            exp.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date+" 00:00:00"));
            //判断amount_money1是否为空，如果为空的话说明该交易金额为负数，否则为整数
            if(StringUtils.isBlank(amount_money1)){
                exp.setAmountMoney((amount_money2==null || amount_money2==undefined) ? null : getBigDecimalByString(amount_money2).negate());
            }else{
                exp.setAmountMoney((amount_money1==null || amount_money1==undefined) ? null : getBigDecimalByString(amount_money1));
            }
            //可用信用额度
            exp.setBalance(getBigDecimalByString(balance));
            //对方卡号
            exp.setOppositeCardNo(opposite_card_no);
            //对方持卡人姓名
            exp.setNameOnOppositeCard(name_on_opposite_card);
            //交易描述
            exp.setDescription(description);
            //卡号
            exp.setCardNum(creditCardAllData.getCardNum());
            //根据交易描述判断
            exp.setCategory(classify(description,expense.getAmountMoney()));
            //编号
            exp.setId(UUID.randomUUID().toString());
            //如果i=0说明币种是人民币；否则是美元
            if(j == 0){
                exp.setCurrencyType("CNY");
            }else if(j==1){
                exp.setCurrencyType("USD");
            }
            expList.add(exp);
        }
    }
    logger.info("任务：{}，最近六个月的消费记录解析完成",context.get(LUA_TASK_KEY));
}

/**
 * 解析信用卡信息
 * @param baseInfoHtml
 * @param creditCardAllData
 * @param unMap
 */
function paraseBaseInfoHtml( baseInfoHtml, creditCardAllData,  unMap) {
    //解析页面
    var doc = Jsoup.parse(baseInfoHtml);
    var tables = doc.select("[class='table1 txt_zt mar01']");
    var table = tables.get(0);
    //获取tr标签
    var trs = table.select("tr");
    for(var i=1;i<trs.size()-1;i++){
        if(i != 7 && i!=8){
            var tds = trs.get(i).select("td");
            //获取字段描述
            var content = tds.get(0).text();
            //获取字段对应的值
            var value = tds.get(1).text();
            //根据字段描述依次赋值
            if(content.contains("卡号")){
                creditCardAllData.setFullCardNum(value);
            }else if(content.contains("查询日期")){

            }else if(content.contains("信用额度")){
                creditCardAllData.setCreditLimit(getBigDecimalByString(value));
            }else if(content.contains("可用额度")){
                creditCardAllData.setBalance(getBigDecimalByString(value));
            }else if(content.contains("取现额度")){
                creditCardAllData.setCashLimit(getBigDecimalByString(value));
            }else if(content.contains("本期应还款金额")){
                unMap.put("min_payment", value);
            }else if(content.contains("本期最低还款金额")){
                unMap.put("min_payment", value);
            }else if(content.contains("本期还款日")){
                unMap.put("payment_due_date", value);
            }else if(content.contains("本期已还款金额")){

            }else if(content.contains("本期未还款金额")){

            }
        }
        logger.info(" ");
    }
    logger.info("");
}

/**
 * 获取请求参数
 * @param detailShortHtml
 * @param map
 * @param beginDate
 * @param endDate
 */
function paraseDetailParams( detailShortHtml, map,  beginDate,  endDate) {
    //解析页面信息
    var doc = Jsoup.parse(detailShortHtml);
    var form1s = doc.select("[name='form1']");
    var form = form1s.get(0);
    var _tokenName = paraseParams(form, "_tokenName");
    var _viewReferer = paraseParams(form, "_viewReferer");
    var AcNo = paraseParams(form, "AcNo");
    var AcType = paraseParams(form, "AcType");
    var AcCur = paraseParams(form, "AcCur");
    var AcSeqNo = paraseParams(form, "AcSeqNo");
    var CifName = paraseParams(form, "CifName");
    var QISHBS2 = paraseParams(form, "QISHBS2");
    var TranId = paraseParams(form, "TranId");
    var OldBeginDate = paraseParams(form, "OldBeginDate");
    var OldEndDate = paraseParams(form, "OldEndDate");
    var flag = paraseParams(form, "flag");
    var isCXflag = paraseParams(form, "isCXflag");
    var helpID = paraseParams(form, "helpID");
    var yanID = paraseParams(form, "yanID");
    var counter1 = paraseParams(form, "counter1");
    var counter2 = paraseParams(form, "counter2");
    var counter3 = paraseParams(form, "counter3");
    var isSearch = paraseParams(form, "isSearch");
    var BeginDatehidden = paraseParams(form, "BeginDatehidden");
    var EndDatehidden = paraseParams(form, "EndDatehidden");
    var gjsearch = paraseParams(form, "gjsearch");
    var SSCFlag = paraseParams(form, "SSCFlag");
    var CHFlag = paraseParams(form, "CHFlag");
    var QISHBS3 = paraseParams(form, "QISHBS3");

    //将获取到的参数放在map中
    map.put("_tokenName", _tokenName);
    map.put("_viewReferer", _viewReferer);
    map.put("AcNo", AcNo);
    map.put("AcType", AcType);
    map.put("AcCur", AcCur);
    map.put("AcSeqNo", AcSeqNo);
    map.put("CifName", CifName);
    map.put("QISHBS2", QISHBS2);
    map.put("TranId", TranId);
    map.put("helpID", helpID);
    map.put("yanID", yanID);
    map.put("counter1", counter1);
    map.put("counter2", counter2);
    map.put("counter3", counter3);
    map.put("BeginDatehidden", BeginDatehidden);
    map.put("EndDatehidden", EndDatehidden);
    map.put("gjsearch", gjsearch);
    map.put("SSCFlag", SSCFlag);
    map.put("CHFlag", CHFlag);
    map.put("QISHBS3", QISHBS3);

    map.put("OldBeginDate", endDate);
    map.put("OldEndDate", beginDate);
    map.put("BeginDate4CX", endDate);
    map.put("EndDate4CX", beginDate);
    map.put("Download", "");
    map.put("flag", "3");
    map.put("isCXflag", "Y");
    map.put("isSearch", "yes");

}

/**
 * 保存卡信息
 * @param debitDepositHtml
 * @param creditCardAllData
 * @param deposits
 */
function paraseDepositHtml( debitDepositHtml,  creditCardAllData,  deposits) {
    //银行
    creditCardAllData.setBankName("光大银行");
    //卡编号
    creditCardAllData.setCardId(UUID.randomUUID().toString());
    var doc = Jsoup.parse(debitDepositHtml);
    //解析页面获取某个元素
    var tables = doc.select("[class='txt02 txt_zt table1']");
    var table = tables.get(0);
    var trs = table.select("[class='td2']");
    if(trs.size()>0){
        var targetTr = trs.get(0);
        var creditCardTimeDeposit = new CreditCardTimeDeposit();
        //获取td元素
        var tds = targetTr.select("td");
        //获取可用信用额度
        var balance = tds.get(6).text();
        var transCurrency = tds.get(1).text();
        var deposit_date = tds.get(4).text();
        var deposit_type = tds.get(0).text();
        //可用信用额度
        creditCardTimeDeposit.setBalance(getBigDecimalByString(balance));
        //存款币种
        creditCardTimeDeposit.setCurrencyType(convertCurr(transCurrency));
        deposit_date = deposit_date.substring(0,4)+"-"+deposit_date.substring(4,6)+"-"+deposit_date.substring(6,8)
        //起息日期
        creditCardTimeDeposit.setDepositDate(yyyy_MM_dd_PARSER.parse(deposit_date));
        //存款类型
        creditCardTimeDeposit.setDepositType(deposit_type);
        //存款利率
        creditCardTimeDeposit.setInterest(null);
        //存期
        creditCardTimeDeposit.setPeriod(null);
        deposits.add(creditCardTimeDeposit);
        //可用信用额度
        creditCardAllData.setBalance(getBigDecimalByString(balance));
        //开卡时间
        creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(deposit_date));
    }
}

/**
 * 抓取未出账单信息
 * @param unbillInfoHtml
 * @param billAllData
 * @param t
 * @param flag
 * @param creditCardAllData
 * @param unMap
 * @param shopping_sheets
 * @returns {boolean}
 */
function parseUnbillHtml( unbillInfoHtml,  billAllData,  t,  flag,  creditCardAllData,  unMap,  shopping_sheets) {
    //解析页面信息
    var undetailDoc = Jsoup.parse(unbillInfoHtml);
    //如果为flag为true
    if(flag){
        //信用额度
        billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
        //最低还款额度
        var min_payment = unMap.get("min_payment");
        billAllData.setMinPayment(getBigDecimalByString(min_payment));
        //还款日
        var payment_due_date = unMap.get("payment_due_date");
        billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(payment_due_date));
    }

    var tables = undetailDoc.select("[class='table1 txt_hui mar01']");
    var table = tables.get(0);
    var trs = table.select("[class='td2']");
    for(var i=0;i<trs.size();i++){
        var exp = new Expense();
        var tr = trs.get(i);
        var tds = tr.select("td");
        var trans_date = tds.get(0).text();
        var post_date = tds.get(1).text();
        var card_num = tds.get(2).text();
        var description = tds.get(3).text();
        var amount_money = tds.get(4).text();
        //消费记录编号
        exp.setId(UUID.randomUUID().toString());
        //交易时间
        exp.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date+" 00:00:00"));
        //记账日期
        exp.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
        //卡号
        exp.setCardNum(card_num);
        //描述
        exp.setDescription(description);
        //交易金额
        exp.setAmountMoney(getAmountToBigDecimal(amount_money));
        //通过描述判断
        exp.setCategory(classify(description,expense.getAmountMoney()));
        //判断币种
        exp.setCurrencyType("CNY");
        //排序
        exp.setOrderIndex(t[0]);
        shopping_sheets.add(exp);
        t[0]++;
    }
    var form1s = undetailDoc.select("[name='form1']");
    var form = form1s.get(0);
    var StartNo = paraseParams(form, "StartNo");
    if(!StartNo.equals("0") && !StartNo.equals("")){
        return true;
    }
    return false;
}

/**
 * 获取未出账单请求的参数
 * @param unbillInfoHtml
 * @param unbillMap
 */
function parseUnbillParams( unbillInfoHtml, unbillMap) {
    //解析未出账单页面
    var billCycleDoc = Jsoup.parse(unbillInfoHtml);
    //获取其name属性
    var form1s = billCycleDoc.select("[name='form1']");
    var form = form1s.get(0);
    //获取请求参数
    var helpID = paraseParams(form, "helpID");
    var yanID = paraseParams(form, "yanID");
    var CardNo = paraseParams(form, "CardNo");
    var CardId = paraseParams(form, "CardId");
    var Org = paraseParams(form, "Org");
    var Orgtxt = paraseParams(form, "Orgtxt");
    var ScreenFlag = paraseParams(form, "ScreenFlag");
    var StartNo = paraseParams(form, "StartNo");
    var StartDate = paraseParams(form, "StartDate");
    var StartType = paraseParams(form, "StartType");
    var _viewReferer = paraseParams(form, "_viewReferer");
    var CONTINUATION_DATA = paraseParams(form, "CONTINUATION_DATA");
    unbillMap.put("helpID", helpID);
    unbillMap.put("yanID", yanID);
    unbillMap.put("CardNo", CardNo);
    unbillMap.put("CardId", CardId);
    unbillMap.put("Org", Org);
    unbillMap.put("Orgtxt", Orgtxt);
    unbillMap.put("ScreenFlag", ScreenFlag);
    unbillMap.put("StartNo", StartNo);
    unbillMap.put("StartDate", StartDate);
    unbillMap.put("StartType", StartType);
    unbillMap.put("_viewReferer", _viewReferer);
    unbillMap.put("CONTINUATION_DATA", CONTINUATION_DATA);
}

/**
 * 获取消费记录
 * @param billAllData
 * @param billDetailHtml
 * @param moth
 * @param flag
 * @param shopping_sheets
 * @param t
 * @returns {boolean}
 */
function parseDetailHtml( billAllData,  billDetailHtml,  moth,  flag,  shopping_sheets,  t) {
    var detailDoc = Jsoup.parse(billDetailHtml);
    //获取最低还款金额和本期剩余应还金额
    if(flag){
        var billCons = detailDoc.select("[class='mar01 txt05 txt_zt']");
        var billCon = billCons.get(0);
        var contents = billCon.text();
        var cons = contents.split("：");
        var new_balance = cons[3].replaceAll("本期最低还款金额", "");
        billAllData.setNewBalance(getBigDecimalByString(new_balance));
        var min_payment = cons[4].replaceAll("本期剩余应还金额", "");
        billAllData.setMinPayment(getBigDecimalByString(min_payment));
    }
    var tabiles = detailDoc.select("[class='table1 txt_hui mar01 ']");
    var table = tabiles.get(0);
    var trs = table.select("[class='td2']");
    for(var i=0;i<trs.size();i++){
        var exp = new Expense();
        var tr = trs.get(i);
        var tds = tr.select("td");
        var trans_date = tds.get(0).text();
        var post_date = tds.get(1).text();
        var card_num = tds.get(2).text();
        var description = tds.get(3).text();
        var amount_money = tds.get(4).text();
        //交易编号
        exp.setId(UUID.randomUUID().toString());
        //交易时间
        exp.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date+" 00:00:00"));
        //记账日
        exp.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
        //卡号
        exp.setCardNum(card_num);
        //描述
        exp.setDescription(description);
        //交易金额
        exp.setAmountMoney(getAmountToBigDecimal(amount_money));
        //根据描述判断消费类型
        exp.setCategory(classify(description,expense.getAmountMoney()));
        //判断币种
        exp.setCurrencyType("CNY");
        //排序
        exp.setOrderIndex(t[0]);
        //账户余额
        exp.setBalance(null);
        shopping_sheets.add(exp);
        t[0]++;
    }
    var form1s = detailDoc.select("[name='form1']");
    var form = form1s.get(0);
    var StartNo = paraseParams(form, "StartNo");
    if(!StartNo.equals("0") && !StartNo.equals("")){
        return true;
    }
    return false;
}

function getAmountToBigDecimal( amount_money) {
    if(amount_money.contains("存入")){
        return getBigDecimalByString(amount_money.replaceAll("存入", "")).negate();
    }else{
        return getBigDecimalByString(amount_money);
    }
}

/**
 * 获取请求参数
 * @param billInfoHtml
 * @param billDetailMap
 * @param element
 * @param num
 */
function parseDetailParams( billInfoHtml, billDetailMap,  element,  num) {
    var billCycleDoc = Jsoup.parse(billInfoHtml);
    var form1s = billCycleDoc.select("[name='"+element+"']");
    var form = form1s.get(0);
    var _savedMap = paraseParams(form, "_savedMap");
    var elements = form.select("[name='_savedMap']");
    var _savedMap2 = elements.get(1).attr("value");
    var helpID = paraseParams(form, "helpID");
    var yanID = paraseParams(form, "yanID");
    var CardId = paraseParams(form, "CardId");
    var Org = paraseParams(form, "Org");
    var Orgtxt = paraseParams(form, "Orgtxt");
    var ScreenFlag = paraseParams(form, "ScreenFlag");
    var StartNo = paraseParams(form, "StartNo");
    var StartDate = paraseParams(form, "StartDate");
    var StartType = paraseParams(form, "StartType");
    var _viewReferer = paraseParams(form, "_viewReferer");
    var firstDate = paraseParams(form, "firstDate");
    var SelectedDate = paraseParams(form, "SelectedDate");
    /* var BillCycle = paraseParams(form, "BillCycle");
     var BillCycle1 = paraseParams(form, "BillCycle1");*/
    billDetailMap.put("_savedMap", _savedMap);
    billDetailMap.put("_savedMap", _savedMap2);
    billDetailMap.put("helpID", helpID);
    billDetailMap.put("yanID", yanID);
    billDetailMap.put("CardId", CardId);
    if(num != 1){
        billDetailMap.put("StartNo", StartNo);
    }
    billDetailMap.put("Org", Org);
    billDetailMap.put("Orgtxt", Orgtxt);
    billDetailMap.put("ScreenFlag", ScreenFlag);
    billDetailMap.put("StartDate", StartDate);
    billDetailMap.put("StartType", StartType);
    billDetailMap.put("_viewReferer", _viewReferer);
    billDetailMap.put("firstDate", firstDate);
    billDetailMap.put("SelectedDate", SelectedDate);
    billDetailMap.put("BillCycle1", "");

}

/**
 * 获取请求参数
 * @param doc
 * @param postdata
 * @param element
 */
function parseParams( doc, postdata, element) {
    //查找某个元素
    var form1s = doc.select("[name='"+element+"']");
    var form = form1s.get(0);
    //获取form中的某个元素的值，作为请求参数
    var _tokenName = paraseParams(form, "_tokenName");
    var helpID = paraseParams(form, "helpID");
    var yanID = paraseParams(form, "yanID");
    var _viewReferer = paraseParams(form, "_viewReferer");
    postdata.put("_tokenName", _tokenName);
    postdata.put("helpID", helpID);
    postdata.put("yanID", yanID);
    postdata.put("_viewReferer", _viewReferer);
}

/**
 * 获取某个元素的值
 * @param form
 * @param element
 * @returns {*}
 */
function paraseParams(form,  element) {
    //获取name属性为某个值得元素
    var elements = form.select("[name='" + element + "']");
    //获取其value值
    var ele = elements.get(0).attr("value");
    return ele;
}


/**
 * 将钱类型进行转换
 * @param val
 * @returns {BigDecimal}
 */
function getBigDecimalByString( val) {
    //将,替换为""
    val = val.replaceAll(",", "");
    //将/RMB替换为""
    val = val.replaceAll("/RMB", "");
    //将人民币：| 转换为""
    val = val.replaceAll("人民币：| ", "");
    //将美元替换为""
    val = val.replaceAll("美元", "");
    //将 替换为""
    val = val.replaceAll(" ", "");
    //将传进来的值滤空
    val = val.trim();
    //将传进来的值转换为bigdecimal类型
    var bigDecimal = new BigDecimal(val);
    return bigDecimal;
}

/**
 * 获取借记卡账单的三个时间段的开始和结束时间
 */
function getBeginAndEndDate(){
    var dateMap = new HashMap();
    var calendar = Calendar.getInstance();
    //今天的时间
    var beginDate1 = yyyy_MM_dd_FORMAT.format(calendar.getTime());
    calendar.add(Calendar.MONTH, -6);
    var endDate1 = yyyy_MM_dd_FORMAT.format(calendar.getTime());
    calendar.add(Calendar.MONTH, -6);
    var endDate2 = yyyy_MM_dd_FORMAT.format(calendar.getTime());
    calendar.add(Calendar.MONTH, -1);
    var endDate3 = yyyy_MM_dd_FORMAT.format(calendar.getTime());
    dateMap.put("beginDate1",beginDate1);
    dateMap.put("endDate1",endDate1);
    dateMap.put("beginDate2",endDate1);
    dateMap.put("endDate2",endDate2);
    dateMap.put("beginDate3",endDate2);
    dateMap.put("endDate3",endDate3);
    return dateMap;
}



//借记卡方法
var debit_commFuns = {
    /**
     * 获取账户的基本信息
     */
    get_debit_card_base_info:function () {
        try {
            logger.info("任务【{}】，光大借记卡开始获取账户管理页面",context.get(LUA_TASK_KEY));
            var debitHtml = ajax_get("https://www.cebbank.com/per/FP020201.do?enterPath=1");
            storeDataToFile(context, debitHtml, "debitHtml.html");
            context.put("ceb_debitHtml",debitHtml);
            logger.info("任务【{}】，光大借记卡获取账户管理页面完成",context.get(LUA_TASK_KEY));
        } catch (e) {
            logger.error("任务【{}】，光大借记卡获取账户管理页面异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }
    },

}

//信用卡方法
var credit_commFuns = {
    /**
     * 获取信用卡账户管理页面
     */
    get_credit_card_base_info:function () {
        try {
            logger.info("任务【{}】，光大信用卡开始获取账户管理页面",context.get(LUA_TASK_KEY));
            var creditHtml = ajax_get("https://www.cebbank.com/per/FP060101.do?enterPath=1");
            storeDataToFile(context, creditHtml, "creditHtml.html")
            context.put("ceb_creditHtml",creditHtml);
            logger.info("任务【{}】，光大信用卡获取账户管理页面完成",context.get(LUA_TASK_KEY));
        } catch (e) {
            logger.error("任务【{}】，光大信用卡获取账户管理页面异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }
    },

    /**
     * 初始化基本信息
     */
    init_credit_card_all_data:function (creditCardAllData,index) {
        try {

        } catch (e) {

        }
    }
}

//通用方法
var commFuns = {
    /**
     * 获取首页信息
     */
    get_index_html:function () {
        logger.info("任务【{}】，光大银行开始获取首页信息",context.get(LUA_TASK_KEY));
        var html = luaFuncs.get_first_html();
        storeDataToFile(context, html, "firstHtml.html")
        context.put("ceb_index_html",html)
        logger.info("任务【{}】，光大银行获取首页信息完成",context.get(LUA_TASK_KEY));
    },

    /**
     * 解析首页信息
     */
    parse_index_html:function () {
        try {
            logger.info("任务【{}】，光大银行开始解析首页信息",context.get(LUA_TASK_KEY));
            var html = context.get("ceb_index_html");
            var doc = Jsoup.parse(html);
            //查找页面上的元素
            var form1s = doc.select("[name='form1']");
            if(form1s.size()>=1){
                var form1 = form1s.get(0);
                //获取某个元素的值
                var EZ_NAME = paraseParams(form1, "EZ_NAME");
                context.put("EZ_NAME", EZ_NAME);
            }
            logger.info("任务【{}】，光大银行解析首页信息完成，抓取到用户名【{}】",context.get(LUA_TASK_KEY),context.get("EZ_NAME"));
        } catch (e) {
            logger.error("taskKey={} 卡信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }
    },
    /**
     * 解析卡片基本信息，卡数量
     */
    parse_card_size:function () {
        try {
            logger.info("任务【{}】，光大银行开始解析信用卡基本信息", context.get(LUA_TASK_KEY));
            var credit_html = context.get("ceb_creditHtml");
            var EZ_NAME = context.get("EZ_NAME");
            var credit_card_list = new ArrayList();
            if (!credit_html.contains("您尚未配置信用卡信息")) {
                logger.info("任务【{}】，发现有信用卡信息，进行抓取", context.get(LUA_TASK_KEY));

                //解析页面
                var credit_doc = Jsoup.parse(credit_html);
                //获取账单信息
                var cardIds = credit_doc.select("[name='CardId']").get(0);
                var options = cardIds.getElementsByTag("option");
                for (var i = 0; i < options.size(); i++) {
                    var cardText = options.get(i).text();
                    logger.info("任务【{}】，cardText={}", context.get(LUA_TASK_KEY), cardText);
                    //判断是否为附属卡 -- 附属卡不做抓取
                    if (cardText.contains("附属卡")) {
                        logger.info("任务【{}】，判断为附属卡，跳出当前卡循环", context.get(LUA_TASK_KEY));
                        continue;
                    }
                    //用于存放卡片的基本信息
                    var credit_map = new LinkedHashMap();
                    var cards = cardText.split("/");
                    //获取卡号
                    var full_card_num = cards[0];
                    //卡号后四位
                    var card_num = full_card_num.substring(full_card_num.length() - 4, full_card_num.length());
                    var name_on_card = cards[2];
                    var open_bank = "光大银行";
                    credit_map.put("full_card_num", full_card_num);
                    credit_map.put("card_num", card_num);
                    credit_map.put("name_on_card", name_on_card);
                    credit_map.put("open_bank", open_bank);
                    //解析请求参数
                    var CardId = options.get(i).attr("value");
                    //解析页面获取请求参数
                    var postdata = new HashMap();
                    postdata.put("delcounter", credit_doc.select("[name='delcounter']").get(0).attr("value"));
                    postdata.put("CardId", CardId);
                    postdata.put("_tokenName", credit_doc.select("input[name='_tokenName']").get(0).attr("value"));
                    postdata.put("helpID", credit_doc.select("input[name='helpID']").get(0).attr("value"));
                    postdata.put("yanID", credit_doc.select("input[name='yanID']").get(0).attr("value"));
                    postdata.put("_viewReferer", credit_doc.select("input[name='_viewReferer']").get(0).attr("value"));
                    credit_map.put("credit_post_data", postdata);
                    credit_card_list.add(credit_map);
                }
            }
            context.put("credit_base_info_list", credit_card_list);
            logger.info("任务【{}】，光大银行信用卡基本信息解析完成，获取到信用卡【{}】张，开始解析借记卡卡列表",context.get(LUA_TASK_KEY),credit_card_list.size());

            var debit_html = context.get("ceb_debitHtml");
            var debitDoc = Jsoup.parse(debit_html);
            //通过id获取
            var bh = debitDoc.getElementById("bh");
            var debit_card_list = new ArrayList();
            if(bh != null){
                var parentTables = debitDoc.select("#bh > table:nth-child(3)")
                if(parentTables!=null) {
                    var cardTables = parentTables.select(".txt02.table1.mar01");
                    for (var s = 0; s < cardTables.size(); s++) {
                        var cardInput = cardTables.get(s).select("[class='td2']").get(0);
                        var inputs = cardInput.select("td");
                        //获取卡片类型
                        var type = inputs.get(3).text();
                        logger.info("任务【{}】，获取到卡类型：" + type, context.get(LUA_TASK_KEY));
                        //卡片是信用卡,循环遍历信用卡结果集将基本信息放入对应的信用卡信息
                        if (!type.contains("信用卡")) {
                            //持卡人姓名
                            var name_on_card = inputs.get(1).text();
                            //卡号
                            var full_card_num = inputs.get(2).text().replaceAll(" ", "");
                            //开户银行
                            var open_bank = inputs.get(4).text();
                            var card_num = full_card_num.substring(full_card_num.length()-4,full_card_num.length())
                            //查询储蓄
                            var cardTable = cardTables.get(s);
                            var paramsStr = cardTable.select("a").get(0).attr("onclick")
                            paramsStr = getGroupByIndex("showHidden\\((.*)\\);", paramsStr, 1).replace(/\'/g,"");
                            var paramsArr = paramsStr.split(",")
                            if(paramsArr.length<=0){
                                return;
                            }
                            var postdata = new HashMap();
                            postdata.put("_viewReferer", "query/queryAsyError");
                            postdata.put("kind", "br");
                            postdata.put("AcNo", paramsArr[5]);
                            postdata.put("AcType", paramsArr[6]);
                            postdata.put("AcOrganId", paramsArr[7]);
                            var debit_map = new LinkedHashMap();
                            debit_map.put("name_on_card",name_on_card);
                            debit_map.put("full_card_num",full_card_num);
                            debit_map.put("open_bank",open_bank);
                            debit_map.put("card_num",card_num);
                            debit_map.put("debit_post_data",postdata);
                            debit_card_list.add(debit_map);
                        }
                    }
                }
            }
            context.put("debit_base_info_list", debit_card_list);
            logger.info("任务【{}】，光大银行借记卡基本信息解析完成，获取到借记卡【{}】张",context.get(LUA_TASK_KEY),debit_card_list.size());
        } catch (e) {
            logger.error("任务【{}】，光大银行用户卡数量基本信息解析异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }
    },

    /**
     * 输入卡数量，构建表头
     */
    create_credit_card_all_data_list:function () {
        logger.info("任务【{}】,开始构建表头",context.get(LUA_TASK_KEY));
        var credit_base_info_list = context.get("credit_base_info_list");
        var debit_base_info_list = context.get("debit_base_info_list");
        if(credit_base_info_list.size() <= 0 && debit_base_info_list.size() <= 0){
            logger.error("任务【{}】,光大银行，未获取到卡列表信息",context.get(LUA_TASK_KEY));
            throw new BankException(BALO_20304_30, errorMsgMap.get(BALO_20304_30));
        }
        if (credit_base_info_list.size() > 0) {
            context.put(keys.CRED_CARD_SIZE,credit_base_info_list.size());
        }
        if (debit_base_info_list.size() > 0){
            context.put(keys.DEBT_CARD_SIZE,debit_base_info_list.size());
        }

        logger.info("任务【{}】,构建表头完成",context.get(LUA_TASK_KEY));
    },

}


var luaFuncs = {
    input_password_gd: function( passWord) {
        var map = new LinkedHashMap();
        map.put("method", "input_password_gd");
        map.put("password", passWord);
        logger.info("send msg : {}", JSON.toJSONString(map));
        return sendAndReceive(map);
    },

    store_Img_gd: function() {
        var map = new LinkedHashMap();
        map.put("method", "store_Img_gs");
        logger.info("send msg : {}", JSON.toJSONString(map));
        return sendAndReceive(map);
    },

    do_login_buttn: function() {
        var map = new LinkedHashMap();
        map.put("method", "do_login_buttn");
        logger.info("send msg : {}", JSON.toJSONString(map));
        return sendAndReceive(map);
    },

    check_sms_input: function() {
        var map = new LinkedHashMap();
        map.put("method", "check_sms_input");
        logger.info("send msg : {}", JSON.toJSONString(map));
        return sendAndReceive(map);
    },

    input_sms_code: function( vcode) {
        var map = new LinkedHashMap();
        map.put("method", "input_sms_code");
        map.put("vcode", vcode);
        logger.info("send msg : {}", JSON.toJSONString(map));
        return sendAndReceive(map);
    },

    get_first_html: function() {
        var map = new LinkedHashMap();
        map.put("method", "get_first_html");
        logger.info("send msg : {}", JSON.toJSONString(map));
        return sendAndReceive(map);
    },

    get_html_gd: function() {
        var map = new LinkedHashMap();
        map.put("method", "get_html_gd");
        logger.info("send msg : {}", JSON.toJSONString(map));
        return sendAndReceive(map);
    }
}
